package com.woniu.woniuproject.controller.admin;

import com.woniu.woniuproject.config.SendSms2;
import com.woniu.woniuproject.entity.Admin;
import com.woniu.woniuproject.exceptions.K15SystemException;
import com.woniu.woniuproject.service.AdminService;
import com.woniu.woniuproject.utils.Md5Utils;
import com.woniu.woniuproject.utils.ResponseResult;
import com.woniu.woniuproject.vo.ARmiddle;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 功能描述:<br>
 * 〈〉
 *
 * @author EDZ
 * @create 2020/11/14
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/admin")
@SessionAttributes({"adminLogin"})
public class AdminController {
    @Autowired
    AdminService adminService;

    @RequestMapping("/administrators")
    public String administrators(@RequestParam("adminname") String adminname,
                                 @RequestParam("password") String password,
                                 Map map) {
        log.debug("账号:{},密码:{}",adminname,password);
        try {
            Subject subject= SecurityUtils.getSubject();
            if (!subject.isAuthenticated()){
                UsernamePasswordToken token=new UsernamePasswordToken(adminname,password);
                subject.login(token);
                //保存管理员信息
                map.put("adminLogin",adminname);
            }
        }catch (UnknownAccountException e){
            log.debug("账号:{}",adminname +"不存在!!!");
            return "0";
        }catch (IncorrectCredentialsException e) {
            log.debug("密码:{}",adminname +"错误!!!");
            return "0";
        }catch (K15SystemException e) {
            log.debug("系统错误!!!");
            return "0";
        }
        return "1" ;
    }
    //显示管理员名字
    @RequestMapping("/queryAdminName")
    public String queryAdminName(ModelMap modelMap){
        String adminLogin = (String) modelMap.getAttribute("adminLogin");
        return adminLogin;
    }
    //退出账户
    @RequestMapping("/logout")
    public void logout(HttpServletRequest request){
        Enumeration em = request.getSession().getAttributeNames();  //得到session中所有的属性名
        while (em.hasMoreElements()) {
         request.getSession().removeAttribute(em.nextElement().toString());
        }
    }

    //修改管理员密码
    @RequestMapping("/updateAdminPass")
    public Integer updateAdminPass(@RequestParam("adminname") String adminname,
                                  @RequestParam("password") String password,
                                   @Param("newpass") String newpass){
        log.debug("账号:{},旧密码:{},新密码:{}",adminname,password,newpass);
        Admin admin = adminService.queryAdminByName(adminname);
        password = Md5Utils.getMd5Pwd("MD5", password, adminname, 1024);
        if (admin.getPassword().equals(password)){//当密码相等时,执行修改
            //加盐加密
            String pass = Md5Utils.getMd5Pwd("MD5", newpass, adminname, 1024);
            int rows=adminService.updateAdminByPass(adminname,pass);
            return rows;
        }
        return 0;
    }
    //查询所有的管理员
    @GetMapping("/queryAdmin")
    public ResponseResult<List<ARmiddle>>getAdminList(@RequestParam(value = "name",defaultValue = "") String name,
                                                   @RequestParam(value = "role",defaultValue = "")String role){
        List<ARmiddle>lists= adminService.queryAdmin(name,role);
       return new ResponseResult<>(lists);
}
    //移除管理员,管理员信息保留
    @DeleteMapping("/deleteAdminbyId")
    public int deleteAdminbyId(@RequestParam("rows") int rows){
        Date date = new Date();
        int row=adminService.UpdatedeleteAdminbyId(rows,date);
        return row;
    }
    //恢复管理员信息
    @GetMapping("/addAdminbyId")
    public  int addAdminbyId(@RequestParam("rows") int rows){
        int row=adminService.UpdateaddAdminbyId(rows);
        return row;
    }
    //验证客户的手机号
    @Autowired
    SendSms2 sendSms2;
    @GetMapping("/queryPhone")
    public String code(@RequestParam("phone")String phone,HttpServletRequest req){
        String codeP = (String) req.getSession().getAttribute("codePhone");
        if (codeP != null){
            req.getSession().removeAttribute("codeP");
        }
        //生成验证码
        String code= UUID.randomUUID().toString().substring(0,4);
        HashMap<String,Object> param=new HashMap<>();
        param.put("code",code);
        //使用验证码
        Map isSend=sendSms2.send(phone,"SMS_205820460",param);

        //设置过期时间
        if ((Boolean) isSend.get("boolean")){
            req.getSession().setAttribute("codePhone",code);
            System.out.println(code+"----------------");
            req.getSession().setMaxInactiveInterval(5*60);
            if (((String) isSend.get("message").toString().substring(12,14)).equals("OK")){
                return "0";
            }else {
                return "1";
            }
        }
        return "2";
    }
    //添加管理员
    @GetMapping("/addAdministration")
    public String addAdministration(@RequestParam("Verification") String Verification,
                                    @RequestParam("adminname") String adminname,
                                    @RequestParam("password") String password,
                                    @RequestParam("phone")String phone,
                                    HttpServletRequest req){
        Admin admin1 = adminService.queryAdminByPhone(phone);
        if(admin1!=null){
            return "3";
        }
        if(adminname!=null&&password!=null&&phone!=null){
            return "2";
        }
        String codeP = (String) req.getSession().getAttribute("codePhone");
        System.out.println(codeP+"========");
        if (!codeP.equals(Verification)){//设置手机号验证码比较
            return "0";
        }
        //设置管理员姓名不可重复
        Admin admin=adminService.queryAdminByName(adminname);
        if (admin!=null){
            return "2";
        }
        password = Md5Utils.getMd5Pwd("MD5", password, adminname, 1024);
        int stu=adminService.addAdmin(adminname,password,phone);
        if (stu>0){
            //查询出刚添加的管理员
            Admin ad=adminService.queryAdminByName(adminname);
            int aId = ad.getAId();
            //根据管理员Id赋给管理员角色
            int rews=adminService.updatearminddle(aId);
            if (rews>0){
                return "1";
            }
        }
        return "0";
    }

    //管理员找回密码
    @GetMapping("/queryRetrievePhone")
    public String queryPhone(@RequestParam("phone")String phone,HttpServletRequest req){
        Admin admin=adminService.queryAdminByPhone(phone);
        if (admin==null){
            return "0"; //管理员手机号不正确
        }
        String codeP = (String) req.getSession().getAttribute("codePhone");
        if (codeP != null){
            req.getSession().removeAttribute("codeP");
        }
        //生成验证码
        String code= UUID.randomUUID().toString().substring(0,4);
        HashMap<String,Object> param=new HashMap<>();
        param.put("code",code);
        //使用验证码
        Map isSend=sendSms2.send(phone,"SMS_205820460",param);
        //设置过期时间
        if ((Boolean) isSend.get("boolean")){
            req.getSession().setAttribute("codePhone",code);
            req.getSession().setMaxInactiveInterval(5*60);
            if (((String) isSend.get("message").toString().substring(12,14)).equals("OK")){
                return "1"; //验证码发送成功
            }else {
                return "2";//验证码发送达到上限
            }
        }
        return "3";//验证码发送失败
    }
    //管理员设置新的密码
    @RequestMapping("/queryRetrievePass")
    public String updateAdminPass(@RequestParam("Verification") String Verification,
                                  @RequestParam("name")String name,
                                   @RequestParam("pass") String pass,
                                  @RequestParam("phone")String phone,
                                   HttpServletRequest req){
        Admin admin=adminService.queryAdminByName(name);
        if (admin==null){
            return "3"; //没有此管理员
        }

        String codeP = (String) req.getSession().getAttribute("codePhone");
        if (!codeP.equals(Verification)){//设置手机号验证码比较
            return "0";  //验证码输入错误
        }
        //加盐加密
        String newpass = Md5Utils.getMd5Pwd("MD5", pass, name, 1024);
        int row=adminService.updateAdminPass(newpass,phone);
        if (row>0){
             return "1";//修改密码成功
        }
        return "2";//修改密码失败

    }
}
